from cryptography.fernet import Fernet
import base64
import os
import sys

class CryptoManager:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._init_crypto()
        return cls._instance

    def _init_crypto(self):
        # 修复：兼容PyInstaller和源码运行的资源路径
        def resource_path(relative_path):
            if hasattr(sys, '_MEIPASS'):
                return os.path.join(sys._MEIPASS, relative_path)
            return os.path.join(os.path.abspath('.'), relative_path)

        key_path = resource_path('resources/.encryption_key')
        # 尝试加载密钥，如果没有则生成新密钥
        if os.path.exists(key_path):
            with open(key_path, 'rb') as f:
                self.key = f.read()
        else:
            self.key = Fernet.generate_key()
            with open(key_path, 'wb') as f:
                f.write(self.key)

        self.cipher = Fernet(self.key)

    def encrypt(self, text: str) -> str:
        """加密文本"""
        encrypted = self.cipher.encrypt(text.encode())
        return base64.urlsafe_b64encode(encrypted).decode()

    def decrypt(self, encrypted_text: str) -> str:
        """解密文本"""
        decoded = base64.urlsafe_b64decode(encrypted_text.encode())
        return self.cipher.decrypt(decoded).decode()

# 全局加密管理器实例
crypto_manager = CryptoManager()

def encrypt(text: str) -> str:
    return crypto_manager.encrypt(text)

def decrypt(encrypted_text: str) -> str:
    return crypto_manager.decrypt(encrypted_text)